package com.ruoyi.aitapp.utils;


import com.alibaba.fastjson.JSONObject;
import com.ruoyi.aitcommon.config.ConfigManager;
import com.ruoyi.aitcommon.utils.ExceptionUtils;
import com.ruoyi.aitcommon.utils.ObjUtils;
import com.ruoyi.aitcommon.utils.SQLUtils;
import com.ruoyi.aitcommon.vo.PageDataVO;
import com.ruoyi.aitcommon.vo.PageInfoVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * APP ERP数据访问
 */
@Component
public class APPDataUtils {
    @Autowired
    ConfigManager configManager;
    @Autowired
    APPConfigUtils appConfigUtils;

    public List<Map<String, Object>> queryERP(String sql) throws Exception {
        final JSONObject db = appConfigUtils.getAPPParamsJson("erpdb");
//        获取DB数据集合
        final List<Map<String, Object>> retlist = SQLUtils.execQuery(sql.toString(), db);
        return retlist;
    }

    /**
     * 根据param参数获取ERP数据
     * @param param 上下文中的参数
     * @param path where条件
     * @param order 排序条件
     * @param pageInfoVO 分页条件
     * @return
     */
    public PageDataVO queryERPByParam(String param,String path,String order, PageInfoVO pageInfoVO) throws Exception {
        PageDataVO ret=new PageDataVO();
        if(ObjUtils.isNotBlank(param)){
            final Object sql = configManager.getContextByParm(param);
            ExceptionUtils.checkBlankOrUndefined(sql,"{}获取SQL为空",param);
            ret = queryERP(sql.toString(),path,order,pageInfoVO);
        }
        return ret;
    }

    public PageDataVO queryERP(String sql,String path,String order, PageInfoVO pageInfoVO) throws Exception {
//        获取DB参数
        final JSONObject db = appConfigUtils.getAPPParamsJson("erpdb");
//            获取记录数
        if(pageInfoVO==null) pageInfoVO=new PageInfoVO();
        int total=SQLUtils.getTotalCnt(sql.toString(), path, db);
        pageInfoVO.setTotalNum(total);
//            获取DB数据集合
        final List<Map<String, Object>> retlist = SQLUtils.execQueryPage(sql.toString(),path,order,(JSONObject) db, pageInfoVO.getPageNum(), pageInfoVO.getPageSize());

//        处理返回值
        PageDataVO ret=new PageDataVO();
        ret.setPageInfo(pageInfoVO);
        ret.setRows(retlist);
        return ret;
    }
}
